package es.ats.codington.spring.controllers;


import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;


import es.ats.codington.festival.services.EventService;
import es.ats.codington.festival.services.PlaceService;
import es.ats.codington.festival.domain.Event;
import es.ats.codington.festival.domain.Imagen;
import es.ats.codington.festival.domain.Place;


/**
 * @author Codington_RED
 *
 */
@Controller
public class AdminController {
	
	/**
	 * Gets places and events added
	 * @param request
	 * @param response
	 * @return "registerevent.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/registerevent.htm", method=RequestMethod.GET) 
	public String registerEventGetController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		try{
			
			
			PlaceService service2 = new PlaceService();
			List<Place> places = new ArrayList<Place>();
			/**
			 * Get all places
			 */
			places = service2.getAllPlaces();
			
			List<Integer> idPlaces = new ArrayList<Integer>();
			List<String> namePlaces = new ArrayList<String>();
			
			
			for (int i = 0; i < places.size(); i++) {
				idPlaces.add(places.get(i).getId());
				namePlaces.add(places.get(i).getNamePlace());
			}
			
			/**
			 * Storing places for id and name
			 */
			Map<Integer, String> aux = new HashMap<Integer, String>();
			for (int i = 0; i < idPlaces.size(); i++) {
				aux.put(idPlaces.get(i), namePlaces.get(i));
			}
			
			request.setAttribute("placeMap", aux);
			
			/**
			 * Redirects registerevent.jsp
			 */
			return "registerevent";
			
			
		} catch (Exception e) {
			
			/**
			 * Redirects error.jsp
			 */
			request.setAttribute("error", e.getMessage());
			return "error";
		} 
	}
	
	/**
	 * Redirects "registerplace.jsp"
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/registerplace.htm", method=RequestMethod.GET) 
	public String registerPlaceGetController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		return "registerplace";
		
	}
	
	/**
	 * Register a place
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/registerplace.htm", method=RequestMethod.POST) 
	public String registerPlacePostController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		try {
			
			String pn = request.getParameter("placename");
			String pd = request.getParameter("placedescription");
			String c = request.getParameter("capacityplace");
			String pz = request.getParameter("placezones");
			String pt = request.getParameter("placetypes");
			
			
			int cN = Integer.parseInt(c);
		
			PlaceService service = new PlaceService();
			Place place = new Place();
			
		    place.setNamePlace(pn);
		    place.setPlaceDescription(pd);
		    place.setCapacityPlace(cN);
		    place.setZonePlace(pz);
		
		    /**
		     *  Insert a place
		     */
		    service.insertPlace(place, pt);
		    
		    /**
		     * Redirects "adminplaces.htm"
		     */
		    return "redirect:/adminplaces.htm";
	
			
		} catch(Exception e) {
			
			/**
			 * Redirects error.jsp
			 */
			request.setAttribute("error", e.getMessage());
			return "error";
		}
		
	}
	
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return "adminevents.htm"
	 * @throws IOException
	 */
	@RequestMapping(value="/registerevent.htm", method=RequestMethod.POST)
	public String registerEventPostController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		try{
			String e = request.getParameter("eventname");
			String ed = request.getParameter("eventdescription");
			String p = request.getParameter("places");
			String d1 = request.getParameter("date1");
			String du1 = request.getParameter("duration1");
			String du2 = request.getParameter("duration2");
			String et = request.getParameter("eventype");
			String a = request.getParameter("availabletickets");
			
			
			int aN = Integer.parseInt(a);
			int pN = Integer.parseInt(p);
			
			
			EventService service = new EventService();
		    
			Event event = new Event();
		     
			event.setName(e);
			event.setDescription(ed);
			event.setPlace("Codington Arena");
			event.setDayEvent(d1);
			event.setStartEvent(du1);
			event.setEndEvent(du2);
			event.setEventType(et);
			event.setSeatsAvailable(aN); 
			event.setIdPlace(pN);
		    
	    	/**
	    	 * Enter an event
	    	 */
	    	service.insertEvent(event);
	    	
	    	/**
			 * Redirects "adminevents.htm"
			 */
	    	return "redirect:/adminevents.htm";
	    
	    		
			} catch (Exception e) {
				
				/**
				 * Redirects error.jsp
				 */
				request.setAttribute("error", e.getMessage());
				return "error";
			} 
		
		
	}
	
	/**
	 * Redirects "adminplaces.htm"
	 * @param request
	 * @param response
	 * @return "adminplaces.htm"
	 * @throws IOException
	 */
	@RequestMapping (value="/updateplace.htm", method = RequestMethod.GET)
	public String updatePlaceGetController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		return "redirect:/adminplaces.htm";
	
	}
	
	/**
	 * Update a place
	 * @param request
	 * @param response
	 * @return "adminplaces.htm"
	 * @throws IOException
	 */
	@RequestMapping (value="/updateplace.htm", method = RequestMethod.POST)
	public String updatePlacePostController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		try{
			
			int idPlace = 0;
			
			/**
			 * Parameters obtained form
			 */
			String pn = request.getParameter("placename");
			String pd = request.getParameter("placedescription");
			String c = request.getParameter("capacityplace");
			String pz = request.getParameter("placezones");
	
				
			int cN = Integer.parseInt(c);
			
			idPlace = (Integer) request.getSession().getAttribute("idPlaceAdminSession");
		
			PlaceService service = new PlaceService();
			Place place = new Place();
			
		    place.setNamePlace(pn);
		    place.setPlaceDescription(pd);
		    place.setCapacityPlace(cN);
		    place.setZonePlace(pz);
		    place.setId(idPlace);
		
			
		    service.updatePlace(place);
		    	
	    	/**
			 * Redirects "adminplaces.htm"
			 */
		    return "redirect:/adminplaces.htm";
		    	
	    	
		} catch (Exception e) {
			
			/**
			 * Redirects error.jsp
			 */
			request.setAttribute("error", e.getMessage());
			return "error";
		} 
	}
		
	/**
	 * Redirects "adminevents.htm"	
	 * @param request
	 * @param response
	 * @return "adminevents.htm"
	 * @throws IOException
	 */
	@RequestMapping (value="/updateevent.htm", method = RequestMethod.GET)
	public String updateEventGetController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		return "redirect:/adminevents.htm";
	
	}
	
	/**
	 * Update a event
	 * @param request
	 * @param response
	 * @return "adminevents.htm"
	 * @throws IOException
	 */
	@RequestMapping (value="/updateevent.htm", method = RequestMethod.POST)
	public String updateEventPostController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		
		try {
		
			int idEvent = 0;
        
			
			String e = request.getParameter("eventname");
			String ed = request.getParameter("eventdescription");
			String p = request.getParameter("places");
			String d1 = request.getParameter("date1");
			String du1 = request.getParameter("duration1");
			String du2 = request.getParameter("duration2");
			String et = request.getParameter("eventype");
			String a = request.getParameter("availabletickets");
			
		
			int aN = Integer.parseInt(a);
			int pN = Integer.parseInt(p);
			
			idEvent = (Integer) request.getSession().getAttribute("idEventAdminSession");
			
			EventService service = new EventService();
		    
			Event event = new Event();
		     
			event.setName(e);
			event.setDescription(ed);
			event.setPlace("Codington Arena");
			event.setDayEvent(d1);
			event.setStartEvent(du1);
			event.setEndEvent(du2);
			event.setEventType(et);
			event.setSeatsAvailable(aN); 
			event.setIdPlace(pN);
			event.setEventID(idEvent);
			
	    
	    	/**
	    	 * The event is updated
	    	 */
	    	service.updateEvent(event);
	    	 
	    	/**
			 * Redirects "adminevents.htm"
			 */
	    	return "redirect:/adminevents.htm";
	    	
		} catch (Exception e) {
			/**
			 * Redirects error.jsp
			 */
			request.setAttribute("error", e.getMessage());
			return "error";
		}
	
	    
	}

	/**
	 * Redirects "adminvisitor.jsp"
	 * @param request
	 * @param response
	 * @return "adminvisitor.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/backpersonaladmin.htm")
	public String backPersonalAdminController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		return "adminvisitor";
	}
	
	/**
	 * Get all events and my events
	 * @param request
	 * @param response
	 * @return "updateeventsadmin.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/adminevents.htm")
	public ModelAndView showEventsController(HttpServletRequest request, HttpServletResponse response) throws IOException {
	
		
		ModelAndView modelandview = new ModelAndView();
		
		try{
			
			PlaceService service2 = new PlaceService();
			List<Place> places = new ArrayList<Place>();
			/**
			 * Get all places
			 */
			places = service2.getAllPlaces();
			
			List<Integer> idPlaces = new ArrayList<Integer>();
			List<String> namePlaces = new ArrayList<String>();
			
			
			for (int i = 0; i < places.size(); i++) {
				idPlaces.add(places.get(i).getId());
				namePlaces.add(places.get(i).getNamePlace());
			}
			
			
			Map<Integer, String> aux = new HashMap<Integer, String>();
			for (int i = 0; i < idPlaces.size(); i++) {
				aux.put(idPlaces.get(i), namePlaces.get(i));
			}
			
			request.setAttribute("placeMap", aux);
			request.getSession().setAttribute("placeMap", aux);
			modelandview.addObject("placeMap", aux);
			
			EventService service3 = new EventService();
			
			List<Event> events = new ArrayList<Event>();
			/**
			 * Get all events
			 */
			events = service3.getAllEvents();
			
			request.getSession().setAttribute("eventsList", events);
			modelandview.addObject("eventsList", events);
			modelandview.setViewName("updateeventsadmin");
			
			
			return modelandview;		

			
		} catch(Exception e){
			/**
			 * Redirects error.jsp
			 */
			request.setAttribute("error", e.getMessage());
			modelandview.setViewName("error");
			return modelandview;
		}		
			
	}
	
	/**
	 * Show places
	 * @param request
	 * @param response
	 * @return "updateplace.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/showplaces.htm", method=RequestMethod.POST)
	public String showPlacesAdminController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int idPlace = 0;
		PlaceService service = new PlaceService();
		
		idPlace = Integer.parseInt(request.getParameter("idPlaceAdmin"));
		request.getSession().setAttribute("idPlaceAdminSession", idPlace);
		
		Place place = new Place();
		place = service.getPlace(idPlace);
		
		request.getSession().setAttribute("namePlace", place.getNamePlace());
		request.getSession().setAttribute("capacityPlace", place.getCapacityPlace());
		request.getSession().setAttribute("descriptionPlace", place.getPlaceDescription());
		request.getSession().setAttribute("zonePlace", place.getZonePlace());
		
		/**
	     * Redirects "updateplace.jsp"
	     */
		return "updateplace";	
	}
	
	/**
	 * Show events
	 * @param request
	 * @param response
	 * @return "updateevent.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/showevents.htm", method=RequestMethod.POST)
	public String showEventsAdminController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int idEvent = 0;
		EventService service = new EventService();
		
		idEvent = Integer.parseInt(request.getParameter("idEventAdmin"));
		request.getSession().setAttribute("idEventAdminSession", idEvent);
		
		Event event = new Event();
		event = service.getEvent(idEvent);
		
		request.getSession().setAttribute("nameEvent", event.getName());
		request.getSession().setAttribute("descriptionEvent", event.getDescription());
		request.getSession().setAttribute("placeName", event.getPlace());
		request.getSession().setAttribute("startEvent", event.getStartEvent());
		request.getSession().setAttribute("endEvent", event.getEndEvent());
		request.getSession().setAttribute("dayEvent", event.getDayEvent());
		request.getSession().setAttribute("typeEvent", event.getEventType());
		request.getSession().setAttribute("seatsAvailableEvent", event.getSeatsAvailable());
		
		
		/**
	     * Redirects "updateevent.jsp"
	     */
		return "updateevent";	
	}
	
	/**
	 * Show places
	 * @param request
	 * @param response
	 * @return "updateplacesadmin.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/adminplaces.htm")
	public ModelAndView showPlacesController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		
		ModelAndView modelandview = new ModelAndView();
		
		try{
			
			
			PlaceService service2 = new PlaceService();
			List<Place> places = new ArrayList<Place>();
			/**
			 * Get all places
			 */
			places = service2.getAllPlaces();
			
			request.setAttribute("placesList", places);
			request.getSession().setAttribute("placesList", places);
			modelandview.addObject("placesList", places);
			
	
			modelandview.setViewName("updateplacesadmin");
			
	
			return modelandview;
		
			
		} catch(Exception e){
			
			/**
			 * Redirects error.jsp
			 */
			request.setAttribute("error", e.getMessage());
			modelandview.setViewName("error");
			return modelandview;
		}		
			
	}
	
	/**
	 * Show image
	 * @param request
	 * @param response
	 * @return "Image.jsp"
	 * @throws IOException
	 */
	@RequestMapping(value="/showimage.htm", method=RequestMethod.GET)
	public String showImgAdminController(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		Imagen img = new Imagen();
		PlaceService service = new PlaceService();
		String route = "C:\\Users\\Sergio\\workspaceindigo\\Codington_red_spring\\WebContent\\Stadium.jpg";
		String name = "img_stadium1";
		img = service.getImage(route, name);
		
	
		String encodedImage = null;
		String imageString = null;
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ImageIO.write((RenderedImage) img.getImage(), "JPEG", os);
		byte[] fileBytes = os.toByteArray();
		encodedImage = Base64.encodeBase64String(fileBytes);
		imageString = "data:image/jpeg;base64,"+encodedImage;
		
		os.close();
		
		request.getSession().setAttribute("imgStadium", imageString);
		
		/**
		 * Redirects "Image.jsp"
		 */
		return "Image";	
	}

}
